#include "mainwindow.h"
#include <QProcess>
#include <QVBoxLayout>
#include <QSpacerItem>
#include <DTitlebar>
#include <DWidgetUtil>
#include <DFrame>
#include <DMessageManager>
#include <QApplication>
#include <QtConcurrent>
MainWindow::MainWindow(QWidget *parent)
    : DMainWindow(parent)
{
    menu=new QMenu;
    reload=new QAction;
    stk=new QStackedWidget;
    out=new QTextEdit;
    listview=new QListWidget;
    DButtonBox *buttonBox = new DButtonBox(titlebar());
    //标题栏按钮
    buttonBox->setFixedWidth(220);
    buttonBox->setButtonList({new DButtonBoxButton("输出内容"), new DButtonBoxButton("设备列表"), new DButtonBoxButton("安装黑阈")}, true);
    buttonBox->setId(buttonBox->buttonList().at(0), 0);
    buttonBox->setId(buttonBox->buttonList().at(1), 1);
    buttonBox->setId(buttonBox->buttonList().at(2), 2);
    QWidget *title=new QWidget;
    QHBoxLayout *titlelayout=new QHBoxLayout;
    title->setLayout(titlelayout);
    titlelayout->addSpacing(160);
    titlelayout->setAlignment(Qt::AlignCenter);
    titlelayout->addWidget(buttonBox);
    titlebar()->setCustomWidget(title);
    buttonBox->setFixedWidth(250);
    buttonBox->buttonList().at(1)->click();

    setMinimumSize(680,610);
    titlebar()->setIcon(QIcon::fromTheme("brevent-enable-tool"));
    setWindowIcon(QIcon::fromTheme("brevent-enable-tool"));
    QLabel *show=new QLabel;
    show->setPixmap(QPixmap(":/page.png"));
    show->setAlignment(Qt::AlignCenter);
    moveToCenter(this);

    menu->addAction(reload);
    titlebar()->setMenu(menu);
    reload->setText("刷新设备列表");
    QWidget* page_0=new QWidget;
    QVBoxLayout* layout_0=new QVBoxLayout;
    page_0->setLayout(layout_0);
    DFrame* out_frame=new DFrame;
    layout_0->addWidget(out_frame);
    out_frame->setLineWidth(0);
    QHBoxLayout* outlayout=new QHBoxLayout;
    out_frame->setLayout(outlayout);
    outlayout->setMargin(0);
    outlayout->addWidget(out);
    out->setLineWidth(0);


    QWidget* page_1=new QWidget;
    QVBoxLayout* layout_1=new QVBoxLayout;
    DFrame* list_frame=new DFrame;
    QHBoxLayout* listlayout =new QHBoxLayout;
    emptylist=new QLabel;
    QFont emptylist_font;
    emptylist_font.setPointSize(18);
    page_1->setLayout(layout_1);
    list_frame->setLayout(listlayout);
    listlayout->addSpacing(50);
    listlayout->addWidget(listview);
    listlayout->addWidget(emptylist);
    listlayout->addSpacing(50);
    layout_1->addWidget(list_frame);
    listview->setLineWidth(0);
    list_frame->setLineWidth(0);
    emptylist->setText("没有发现设备");
    emptylist->setAlignment(Qt::AlignCenter);
    emptylist->setFont(emptylist_font);
    listview->hide();


    btn_install=new QPushButton;
    spinner=new DSpinner;
    spinner->setFixedSize(64,64);
    QWidget* page_2=new QWidget;
    QVBoxLayout* layout_2=new QVBoxLayout;
    DFrame* frame_2=new DFrame;
    frame_2->setLineWidth(0);
    page_2->setLayout(layout_2);
    layout_2->addWidget(frame_2);
    QVBoxLayout* layout_2f=new QVBoxLayout;
    QHBoxLayout* layout_btn=new QHBoxLayout;
    frame_2->setLayout(layout_2f);
    QLabel* label_2=new QLabel;
    QLabel* label_install=new QLabel;
    label_2->setText("手机扫描二维码下载安装");
    label_2->setAlignment(Qt::AlignCenter);
    QFont font_2;
    layout_2f->setAlignment(Qt::AlignCenter);
    font_2.setPixelSize(24);
    label_2->setFont(font_2);
    label_2->setFixedHeight(130);
    layout_2f->addWidget(label_2);
    layout_2f->addWidget(show);
    show->setFixedHeight(240);
    layout_2f->addSpacing(50);
    layout_2f->addLayout(layout_btn);
    layout_btn->addWidget(btn_install);
    layout_2f->addSpacing(10);
    layout_2f->addWidget(label_install);
    layout_2f->addStretch();
    layout_btn->addWidget(spinner);
    spinner->start();
    label_install->setText("");
    label_install->setAlignment(Qt::AlignCenter);
    spinner->hide();
    btn_install->setFixedSize(200,38);
    btn_install->setText("一键安装最新版本到手机");
    connect(btn_install,&QPushButton::clicked,[=](){
        QtConcurrent::run([=](){ //实现下载最新版
            if(listview->currentItem()!=nullptr){
                btn_install->hide();
                spinner->show();
                label_install->setText("正在下载");
                QProcess download;
                download.start("wget https://dl.jianyv.com/br/latest.apk -O /tmp/br.apk");
                download.waitForFinished();
                QFile file("/tmp/br.apk");
                file.open(QFile::ReadOnly);
                auto filebty=file.readAll();
                if(!filebty.isEmpty()){
                    file.close();
                    label_install->setText("正在安装");
                    QProcess run;
                    run.start("adb -s "+listview->currentItem()->text()+" install /tmp/br.apk");
                    run.waitForFinished();
                    QString output;
                    output=run.readAll();
                    output.remove("\n");
                    output.remove(" ");
                    output.remove("\t");
                    out->append("安装到手机\n adb -s "+listview->currentItem()->text()+" install /tmp/br.apk");
                    out->append(output);
                    if(output!="Success"){
                        label_install->setText("可能遇到了一些错误，安装失败");
                    }else {
                        label_install->setText("成功到安装到设备");
                    }
                }else {
                    label_install->setText("下载失败");
                }
            }else {
                label_install->setText("你并没有选中任何设备");
            }


            spinner->hide();
            btn_install->show();
        });

    });

    layout_2f->addSpacing(100);


    setCentralWidget(stk);
    stk->addWidget(page_0);
    stk->addWidget(page_1);
    stk->addWidget(page_2);

    connect(buttonBox, &DButtonBox::buttonClicked, this, [=](QAbstractButton *button) {
        stk->setCurrentIndex(buttonBox->id(button));
        listview->setFocus();
        if(buttonBox->id(button)==1){
            update_dev();
        }
    });
    stk->setCurrentWidget(page_1);
    out->setReadOnly(true);
    connect(reload,&QAction::triggered,[=](){update_dev();});
    update_dev();
    connect(listview,&QListView::doubleClicked,[=](){

        if(listview->currentItem()!=nullptr){
            out->append("正在激活");
            QProcess run;
            QString cmd;
            cmd="adb ";
            cmd+="-d -s ";cmd+=listview->currentItem()->text();
            cmd+=" shell sh /data/data/me.piebridge.brevent/brevent.sh";
            run.start(cmd);
            run.waitForFinished();
            QString outstr=run.readAllStandardOutput();
            out->append(cmd);
            out->append(outstr);
            if(outstr.contains("pid:")){
                out->append("执行结束，请检查是否激活成功。\n");
                DMessageManager::instance()->sendMessage(this, style()->standardIcon(QStyle::SP_DialogOkButton),"激活成功");
            }else {
                out->append("激活失败，请联系开发者寻找问题maicss<maicss@126.com>。\n");
                DMessageManager::instance()->sendMessage(this, style()->standardIcon(DStyle::SP_MessageBoxCritical),"激活失败，您可以重新打开USB调试或者重启手机后重试");

            }

        }else {
            out->append("请选择要激活的设备号，若上边列表为空，请检查是否插入设备并刷新重试。\n");
        }
    });
    connect(DGuiApplicationHelper::instance(), &DGuiApplicationHelper::themeTypeChanged, this, [=](DGuiApplicationHelper::ColorType themeType) {
        QColor main_color;
        main_color=DGuiApplicationHelper::instance()->applicationPalette().highlight().color();
        if(themeType==DGuiApplicationHelper::DarkType){
            qDebug()<<"Dark";
            show->setPixmap(QPixmap(":/page_dark.png"));
        }else {
            qDebug()<<"Light";

            show->setPixmap(QPixmap(":/page.png"));

        }
    });

}

MainWindow::~MainWindow()
{

}

void MainWindow::update_dev()
{
    listview->hide();
    QProcess run;
    run.start("adb devices");
    run.waitForFinished();
    QString str=run.readAllStandardOutput();
    str.remove("\n\n");
    out->append("刷新列表\n"+str+"\n");

    QStringList list=str.split("\n");
    listview->clear();
    QFont font;
    font.setPointSize(18);

    for (int i=listview->count()-1;i>=0;i--) {
        delete listview->item(i);
    }
    for(int i=1;i<list.size();i++){
        QString dev=list[i];
        dev=dev.simplified();
        if(!dev.isEmpty() || dev==" "){
            QStringList tmp=dev.split(" ");
            QListWidgetItem *item=new QListWidgetItem(tmp[0]);
            item->setSizeHint(QSize(50,50));
            item->setFont(font);
            item->setTextAlignment(Qt::AlignCenter);
            listview->addItem(item);
            listview->setCurrentItem(item);
        }
    }
    if(listview->count()==0){
        emptylist->show();
        listview->hide();
        DMessageManager::instance()->sendMessage(this, style()->standardIcon(QStyle::SP_MessageBoxWarning),"没有发现设备，请检查是否接入设备\n或者设备是否已经打开USB调试");
    }else {
        emptylist->hide();
        listview->show();
        DMessageManager::instance()->sendMessage(this, style()->standardIcon(QStyle::SP_MessageBoxInformation),"刷新列表成功，发现设备，双击开始激活");
    }
    listview->setFocus();
}
